<template>
  <Container class="single-sale">
    <div class="container-header title title-center" slot="header">
      <Button size="large" class="fl btn-back"  icon="ios-arrow-back" @click="onEditRule">返回</Button>
      优惠券
    </div>
    <div class="bg-light">
      <div class="container-title">
        <span>优惠券规则</span>
      </div>
      <Form :label-width="136" ref="form">
        <Row>
          <Col span="8">
            <FormItem label="优惠券类别：">{{couponDiscountTypeMap[info.couponDiscountType]}}</FormItem>
            <FormItem label="促销类型：">{{couponPromotionTypeMap[info.couponPromotionType]}}</FormItem>
            <FormItem label="使用期限：">{{info.date}}</FormItem>
            <FormItem label="发放渠道：">{{info.couponSendChannelEnum | SendChannelFilter}}</FormItem>
            <FormItem label="设置：">{{info.couponStatus === 'OPEN' ? '启用' : '未启用'}}</FormItem>
          </Col>
          <Col span="8">
            <FormItem label="优惠券名称：">{{info.couponName}}</FormItem>
            <FormItem label="优惠券面额：" v-if="info.couponDiscountType!='DISCOUNT_COUPON'">{{info.denomination}}</FormItem>
            <FormItem label="发行量：">{{info.amount}}</FormItem>
            <FormItem label="优惠券说明：">{{info.remark}}</FormItem>
            <FormItem label="每个商品能用：" v-if="info.couponDiscountType === 'DENOMINATION_COUPON' && info.useQuantityPerProduct">{{info.useQuantityPerProduct}}张</FormItem>
            <FormItem label="优惠券使用类型：">{{info.couponUseQuantityTypeEnum | couponUseFilter}}</FormItem>
          </Col>
          <Col span="8">
            <FormItem label="使用条件：">{{info.couponDiscountType == 'DISCOUNT_COUPON' ? info.discount : info.useCondition}}</FormItem>
            <FormItem label="限领：">
              {{info.receiveLimitType === 'LIMIT_NONE' ? '不限制' : info.receiveLimitType === "LIMIT_ONE" ? `每人限领${info.receiveLimitQuantity}张` : `每人每天限领${info.receiveLimitQuantity}张`}}
            </FormItem>
            <FormItem label="优惠券类型：">{{info.couponType === '1' ? '商品券' : '平台券'}}</FormItem>
            <FormItem label="是否公开：">{{info.isPublic ? '公开' : '不公开'}}</FormItem>
            <FormItem v-if="info.couponDiscountType === 'DENOMINATION_COUPON'" label="使用权重：">{{ info.weights }}</FormItem>
          </Col>
        </Row>
      </Form>
      <Loader :status="detailStatus" @refresh="getData"></Loader>
    </div>
    <div class="bg-light mt">
        <div class="container-header">
          <Form class="search">
            <Row>
              <Col span="6">
                <FormItem label="店铺类目">
                  <ShopSelect v-model="list.form.ownerCategoryId" @input="onClickSearch"></ShopSelect>
                  <!-- <CategorySelect v-model="list.form.categoryId"></CategorySelect> -->
                </FormItem>
              </Col>
              <Col span="6">
                <FormItem label="商品品牌">
                  <BrandSelect v-model="list.form.brandId" @input="onClickSearch"></BrandSelect>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="商品名称">
                  <Input v-model="list.form.keyword" clearable @on-enter="onClickSearch" :maxlength="100" placeholder="请输入商品名称"/>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="商品编码">
                  <Input v-model="list.form.code" clearable @on-enter="onClickSearch" :maxlength="30" placeholder="请输入商品编码"/>
                </FormItem>
              </Col>
              <Col span="2" class-name="search small">
                <Button class="btn-search" type="primary" icon="ios-search" @click="onClickSearch"></Button>
              </Col>
            </Row>
          </Form>
        </div>
        <Tabs v-model="tab" @on-click="onChangeSelect" v-if="type==='DENOMINATION_COUPON'">
          <Button type="primary" icon="md-add" slot="extra" class="item mr" @click="onBatchAdd" v-if="tab === 'tab1'">批量加入</Button>
          <Button type="primary" icon="md-add" slot="extra" class="item mr" @click="onBatchDelete" v-else>批量撤出</Button>
          <TabPane label="新增活动商品" name="tab1">
            <Table
                ref="productTable"
                :height="options.tableHeight"
                stripe
                :columns="list.columns"
                :data="list.data"
                @on-selection-change="onSelectProduct"
                no-data-text="亲，没有找到相关记录哦！~">
            </Table>
            <div class="pager">
                <Page
                :total="list.totalItem"
                :current="list.currentPage"
                :page-size="list.pageSize"
                @on-change="onPageChange"
                @on-page-size-change="onPageSizeChange"
                show-sizer
                placement="top">
                </Page>
            </div>
            <Loader :status="list.status" @refresh="getProductData"></Loader>
          </TabPane>
          <TabPane :label="'已参加的活动商品('+selectedList.selectedPage+')'" name="tab2">
            <Table
                ref="selectedTable"
                :height="options.tableHeight"
                stripe
                :columns="selectedList.columns"
                :data="selectedList.data"
                @on-selection-change="onDeleteProduct"
                no-data-text="亲，没有找到相关记录哦！~">
            </Table>
            <div class="pager">
                <Page
                :total="selectedList.totalItem"
                :current="selectedList.currentPage"
                :page-size="selectedList.pageSize"
                @on-change="onSelectedPageChange"
                @on-page-size-change="onSelectedPageSizeChange"
                show-sizer
                placement="top">
                </Page>
            </div>
            <Loader :status="list.status" @refresh="getSelectedData"></Loader>
          </TabPane>
        </Tabs>
        <Tabs v-model="discountTab" v-else @on-click="onTabsClick">
          <Button type="primary" icon="md-add" slot="extra" class="item mr" v-if="discountTab !=='discountTab1'" @click="toBatchNewProduct">批量撤出</Button>
          <template v-for="(item, index) in discountGroupList">
            <Button  :key="index" v-if="discountTab =='discountTab1'" type="primary" slot="extra" class="item" @click="toLevelItem(index)">
              {{discountTextArr[index]}}
            </Button>
          </template>
          <TabPane label="新增活动商品" name="discountTab1">
            <Table
                ref="productTable"
                stripe
                :columns="discountList.columns"
                :data="list.data"
                @on-selection-change="onSelectLevle"
                :height="options.tableHeight"
                no-data-text="亲，没有找到相关记录哦！~">
            </Table>
            <div class="pager">
                <Page
                :total="list.totalItem"
                :current="list.currentPage"
                :page-size="list.pageSize"
                @on-change="onPageChange"
                @on-page-size-change="onPageSizeChange"
                show-sizer
                placement="top">
                </Page>
            </div>
            <Loader :status="list.status" @refresh="getProductData"></Loader>
          </TabPane>
          <TabPane v-for="(item, index) in discountGroupList" :key="index" :label="item.group + '阶:' + item.discount + '折' + '(' + levelList.levelPageData[index].selectedPage + ')'" :name="'discountTab' + (index + 2)">
            <Table
                :ref="'discountTable' + (index + 2)"
                :height="options.tableHeight"
                stripe
                :columns="levelList.columns"
                :data="levelList.data[index]"
                no-data-text="亲，没有找到相关记录哦！~">
            </Table>
            <div class="pager">
                <Page
                  :total="levelList.levelPageData[index].totalItem"
                  :current="levelList.levelPageData[index].currentPage"
                  :page-size="levelList.levelPageData[index].pageSize"
                  @on-change="onLevelListPageChange($event,index)"
                  @on-page-size-change="onLevelListPageSizeChange($event,index)"
                  show-sizer
                  placement="top">
                </Page>
            </div>
            <Loader :status="list.status" @refresh="getSelectedData(index + 1, index)"></Loader>
          </TabPane>
        </Tabs>
      </div>
      <div class="container-footer bg-white" slot="footer">
        <Button type="primary" size="large" @click="onOpen" :disabled="info.couponStatus === 'OPEN'">启用</Button>
      </div>
  </Container>
</template>
<script>
import { mapGetters } from 'vuex'
import { formatDate, formatCurrency } from '@/util'
// import CategorySelect from '@/components/CategorySelect'
import BrandSelect from '@/components/BrandSelect'
import ShopSelect from '@/components/ShopSelect'
import listData from './edit/NewEditData'
import selectedData from './edit/SelectedEditData'
import discountData from './edit/DiscountEditData'
import levelItemData from './edit/LevelEditData'

export default {
  components: {
    ShopSelect,
    BrandSelect
  },
  data() {
    return {
      detailStatus: 'pass',
      couponId: this.$route.query.couponId || null,
      options: {
        tableHeight: 450
      },
      //优惠券类别
      couponDiscountTypeMap: {
        DENOMINATION_COUPON: '满减券',
        DISCOUNT_COUPON: '折扣券',
        CASH_COUPON: '现金券'
      },
      //促销类型
      couponPromotionTypeMap: {
        FACTORY_ACTIVE_COUPON: '工厂促销券',
        FULL_COUPON_ACTIVE_COUPON: '满额返券促销券',
        GENERAL_COUPON: '普通券'
      },
      info: {},
      tab: 'tab1',
      discountTab: 'discountTab1',
      list: listData,
      discountList: discountData,
      levelList: levelItemData,
      selectTarget: [],
      deleteTarget: [],
      selectedList: selectedData,
      btnDisable: false,
      type: 'DENOMINATION_COUPON',
      discountGroupList: [],
      discountGroupData: { 0: [], 1: [], 2: [], 3: [], 4: [] },
      discountTextArr: ['加入一阶', '加入二阶', '加入三阶', '加入四阶', '加入五阶'],
      levelSelection: [],
      selectedListData: [], //已参加活动商品分页展示数据
      selectedLevelListData: { 0: [], 1: [], 2: [], 3: [], 4: [] }, //一阶二阶三阶四阶五阶分页展示数据
      groupIndex: 0,
      couponStatusEnum: false  // 启用状态
    }
  },
  mounted() {
    // this.$store.dispatch('getRankList')
    this.selectedList.data = []
    this.list.currentPage = 1
    this.getData()
    this.getProductData()
    // if (this.info.discountGroupList.length > 1) {
    //   for (let i = 0; i < this.info.discountGroupList.length; i++) {
    //     this.getSelectedData( i + 1, i )
    //   }
    // } else { // 满减券
    //   this.getSelectedData()
    // }
    this.$bus.$on('onChangeState', ({ type, item }) =>
      this.onChangeState(type, item)
    )
    this.$bus.$on('onDeleteSelect', ({ type, item, index }) =>
      this.onDeleteSelect(type, item, index)
    )
    this.$bus.$on('toNewProduct', ({ item }) =>
      this.toNewProduct(item)
    )
  },
  destroyed() {
    this.$bus.$off()
  },
  methods: {
    getData() {
      this.detailStatus = 'loading'
      this.$ajaxGet(`/coupon/coupon_info/detail/${this.couponId}`).then(data => {
        this.detailStatus = 'pass'
        this.info = data
        this.type = this.info.couponDiscountType
        this.info.date = (this.info.validityStartDate && this.info.validityEndDate) ? formatDate(this.info.validityStartDate, true) + '-' + formatDate(this.info.validityEndDate, true) : this.info.validityDays 
        if (this.info.couponDiscountType === 'DISCOUNT_COUPON') { //折扣券
          this.discountGroupList = this.info.discountGroupList
          let len = Object.keys(this.discountGroupList).length
          this.info.discount = this.discountGroupList[0].discount + '折~' + this.discountGroupList[len - 1].discount + '折'
          this.info.useCondition = null
        } else {
          this.info.useCondition = formatCurrency(this.info.useCondition, true)
          this.info.discount = null
        }
        this.info.denomination = formatCurrency(this.info.denomination, true)
        if (this.info.discountGroupList && this.info.discountGroupList.length > 1) {
          for (let i = 0; i < this.info.discountGroupList.length; i++) {
            this.getSelectedData( i + 1, i )
          }
        } else { // 满减券
          this.getSelectedData()
        }
      }).catch(() => {
        this.detailStatus = 'error'
      })

      // let couponForm = JSON.parse(sessionStorage.getItem('couponForm'))
      // // let str = ''
      // if (couponForm) {
      //   this.info = couponForm
      //   this.type = this.info.couponDiscountType //优惠券的类型
      //   this.discountGroupList = this.info.discountGroupList //打折的阶梯
      //   if (couponForm.showDate) {
      //     this.info.date = formatDate(new Date(couponForm.validityDate[0]), true) + '-' + formatDate(new Date(couponForm.validityDate[1]), true)
      //   } else {
      //     this.info.date = couponForm.validityDays + '天'
      //   }
      //   if (this.info.couponDiscountType === 'DISCOUNT_COUPON') { //折扣券
      //     let len = Object.keys(this.discountGroupList).length
      //     this.info.discount = this.discountGroupList[0].discount + '折~' + this.discountGroupList[len - 1].discount + '折'
      //     this.info.useCondition = null
      //   } else {
      //     this.info._useCondition = couponForm.useCondition
      //     this.info.useCondition = formatCurrency(couponForm.useCondition, true)
      //     this.info.discount = null
      //   }
      //   this.info.denomination = couponForm.showNum ? formatCurrency(couponForm.diyMoney, true) : formatCurrency(couponForm._denomination, true)
      // }
    },
    getSelectedData(groups = 1, index = 0) { // 查询已选中的商品
      let param = {
        brandId: this.list.form.brandId,
        ownerCategoryId: this.list.form.ownerCategoryId,
        keyword: this.list.form.keyword,
        code: this.list.form.code,
        couponId: this.couponId
      }
      this.list.status = 'loading'
      if (this.info.couponDiscountType === 'DENOMINATION_COUPON') {
        param.size = this.selectedList.pageSize
        param.current = this.selectedList.currentPage
      } else { // 满减券
        param.groups = groups
        param.size = this.levelList.levelPageData[index].pageSize
        param.current = this.levelList.levelPageData[index].currentPage
      }
      this.$ajaxGet('/coupon/coupon_info/product/spu_page', param).then(data => {
        this.list.status = 'pass'
        if (this.info.couponDiscountType === 'DENOMINATION_COUPON') {
          this.selectedList.data = data.records || []
          this.selectedList.totalItem = Number(data.total)
          this.selectedList.selectedPage = Number(data.productId.length)
        } else {
          this.$set(this.levelList.data, index, data.records)
          this.levelList.levelPageData[index].totalItem = Number(data.total)
          this.levelList.levelPageData[index].selectedPage = Number(data.productId.length)
        } 
      })
    },
    onChangeSelect() {
      this.resetSearch()
      if (this.tab === 'tab1') {
        this.getProductData()
      } else {
        this.getSelectedData()
      }
    },
    onClickSearch () {
      if (this.info.couponDiscountType === 'DENOMINATION_COUPON') {
        if (this.tab === 'tab1') {
          this.list.currentPage = 1
          this.getProductData()
        } else {
          this.selectedList.currentPage = 1
          this.getSelectedData()
        }
      } else {
        if (this.discountTab === 'discountTab1') {
          this.list.currentPage = 1
          this.getProductData()
        } else {
          this.levelList.levelPageData[this.groupIndex -1].currentPage = 1
          this.getSelectedData(this.groupIndex, this.groupIndex -1)
        }
      }
    },
    async getProductData() {
      let param = {
        brandId: this.list.form.brandId,
        ownerCategoryId: this.list.form.ownerCategoryId,
        keyword: this.list.form.keyword,
        code: this.list.form.code,
        size: this.list.pageSize,
        current: this.list.currentPage
      }
      this.list.status = 'loading'
      await this.$ajaxGet('/coupon/coupon_info/product/spu_page', param).then(data => {
        data.records = data.records || []
        this.list.data = data.records.map(item => {
          return {
            ...item
          }
        })
        this.list.totalItem = Number(data.total)
        this.list.status = 'pass'
      }).catch(() => {
        this.list.status = 'error'
      })
    },
    toLevelItem(index) {
      if (this.levelSelection.length === 0) {
        this.$Notice.warning({
          title: '提醒',
          desc: '请先选择商品!'
        })
        return
      }
      this.onChangeState(1, null, index + 1)
    },
    onSelectLevle(selection) {
      this.levelSelection = selection
    },
    onChangeState(type, item, groups = 1) {
      this.list.status = 'loading'
      let param = {
        couponId: this.couponId
      }
      if (this.info.couponDiscountType === 'DENOMINATION_COUPON') { // 满减券
        if (type === 2) { // 批量加入
          param.couponProductList = this.selectTarget.map(m => {
            return {
              spuId: m.id,
              groups: 1
            }
          })
        } else { // 单个加入
          param.couponProductList = [{
            spuId: item.id,
            groups: 1
          }]
        }
      } else { // 折扣券
        if (type === 1) {
          param.couponProductList = this.levelSelection.map(m => {
            return {
              spuId: m.id,
              groups
            }
          })
        }
      }
      this.$jsonPost('/coupon/coupon_info/save_product', param).then(res => {
        this.list.status = 'pass'
        this.$Notice.success({
          title:"加入成功"
        })
        this.getSelectedData(groups, groups-1)
        this.$refs.productTable.selectAll(false) // 取消勾中的数据
        this.selectTarget = []
        this.levelSelection = []
      }).catch(() => {
        this.list.status = 'error'
      })
    },
    onSelectProduct(selection) {
      this.selectTarget = selection
    },
    onDeleteProduct(selection) {
      this.deleteTarget = selection
    },
    onBatchAdd() {
      if (!this.selectTarget.length) {
        this.$Message.warning('请选择商品')
        return
      }
      this.onChangeState(2)
    },
    toNewProduct(item, index) {
      this.onDeleteSelect(1, item, index)
    },
    toBatchNewProduct() {
      this.onDeleteSelect()
    },
    onDeleteSelect(type, item, index) {
      this.list.status = 'loading'
      let param = {
        couponId: this.couponId
      }
      if (this.info.couponDiscountType === 'DENOMINATION_COUPON') {
        if (type === 1) { // 单个撤出
          param.ids = [item.id]
        } else { // 批量撤出
          param.ids = this.deleteTarget.map(m => m.id)
        }
      } else if (this.info.couponDiscountType === 'DISCOUNT_COUPON'){ // 折扣券批量撤出 
        if (type === 1) { // 单个撤出
          param.ids = [item.id]
        } else {
          let tabIndex = this.discountTab.replace('discountTab', "discountTable")
          param.ids = (this.$refs[`${tabIndex}`][0].getSelection() || []).map(m => m.id)
        }
      } else {
        param.ids = [item.id]
      }
      this.$ajaxPost('/coupon/coupon_info/delete_product', param).then(data => {
        this.$Notice.success({
          title: '删除成功'
        })
        this.list.status = 'pass'
        if (this.info.couponDiscountType === 'DENOMINATION_COUPON') {
          if (type === 1) {
            this.selectedList.data.splice(index, 1)
          } else {
            this.getSelectedData()
          }
        } else {
          this.getSelectedData(this.groupIndex, this.groupIndex -1)
        }
      })
    },
    onBatchDelete() {
      if (!this.deleteTarget.length) {
        this.$Message.warning('请选择商品')
        return
      }
      this.onDeleteSelect(2)
    },
    onSelectedPageChange(number) {
      this.selectedList.currentPage = number
      this.getSelectedData()
    },
    onSelectedPageSizeChange(pageSize) {
      this.selectedList.pageSize = pageSize
      this.selectedList.currentPage = 1
      this.getSelectedData()
    },
    onPageChange(number) {
      this.list.currentPage = number
      this.getProductData()
    },
    onPageSizeChange(pageSize) {
      this.list.currentPage = 1
      this.list.pageSize = pageSize
      this.getProductData()
    },
    onLevelListPageChange (current, index) {
      this.levelList.levelPageData[index].currentPage = current
      this.getSelectedData(this.groupIndex, this.groupIndex -1)
    },
    onLevelListPageSizeChange (pageSize, index) {
      this.levelList.levelPageData[index].currentPage = 1
      this.levelList.levelPageData[index].pageSize = pageSize
      this.getSelectedData(this.groupIndex, this.groupIndex -1)
    },
    onTabsClick () {
      this.resetSearch()
      if (this.discountTab === 'discountTab1') {
        this.getProductData()
      } else {
        this.groupIndex = this.discountTab.charAt(this.discountTab.length - 1) - 1
        this.getSelectedData(this.groupIndex, this.groupIndex -1)
      }
    },
    resetSearch() {
      this.list.form.brandId = null
      this.list.form.ownerCategoryId = null
      this.list.form.keyword = null
      this.list.form.code = null
    },
    onEditRule() {
      let type = this.$route.query.type || ''
      if (type === 'editgood') {
        this.$router.back()
      } else {
        this.$router.push({
          name: 'coupon/add',
          query: {
            couponId: this.couponId
          }
        })
      }
    },
    jumpPage() {
      sessionStorage.removeItem('couponForm')
      this.$router.push({
        name: 'sales/coupon/list'
      })
    },
    onOpen() {
      this.$Modal.confirm({
        title: '确认',
        content: '确认启用？',
        onOk: () => {
          let param = {
            couponId: this.couponId,
            couponStatusEnum: 'OPEN'
          }
          this.$ajaxPost('/coupon/coupon_info/close', param).then(() => {
            this.$Notice.success({
              title: '操作成功'
            })
            this.info.couponStatus = 'OPEN'
            this.$router.push({
              name: 'sales/coupon/list',
              query: {
                currentPage: 1,
                tab: 'tab1'
              }
            })
          }).catch(() => {
            this.info.couponStatus = 'NO_OPEN'
          })
        }
      })
    },
  },
  filters: {
    SendChannelFilter(v) {
      let list = {
        'NONE_LIMIT': '不限',
        'TIRE_INSURANCE': '轮胎保小程序',
        'CLOUD_APP': '中策云店',
        'SALESMAN': '业务通'
      }
      return list[v]
    },
    couponUseFilter(v) {
      let list = {
        'NONE_LIMIT': '不限',
        'PRODUCT_LIMIT': '限商品',
        'LIMIT_ONE': '每单限1张'
      }
      return list[v]
    }
  }
}
</script>

